package com.ShangGuiGu.stack;

import java.util.Scanner;

/**
 * @auther zsj
 * @Date 2022/1/10
 * <p>
 * 栈
 * 数据结构
 * 先入后出的特点
 * 数组模拟栈
 * <p>
 * 栈顶
 * 出栈
 * 入栈
 **/
public class ArrayStackDemo {
    public static void main(String[] args) {
        ArrayStack arrayStack = new ArrayStack(5);

        Scanner scanner = new Scanner(System.in);
        boolean loop = true;//控制是否退出菜单
        String key = "";
        while (loop) {
            System.out.println("show查看栈中所有数据");
            System.out.println("exit退出程序");
            System.out.println("push添加数据");
            System.out.println("pop出栈");
            System.out.println("输入您的选择");
            key =scanner.next();
            switch (key) {
                case "show":
                    arrayStack.list();
                    break;
                case "push":
                    if (arrayStack.isFull()) {
                        System.out.println("栈满");
                        break;
                    } else {
                        System.out.println("请输入你想输入的数字");
                        int value = scanner.nextInt();
                        arrayStack.push(value);
                        break;
                    }
                case "pop":
                    int pop = arrayStack.pop();
                    System.out.printf("出栈的数据是%d\n",pop);
                    break;
                case "exit":
                    scanner.close();
                    loop=false;
            }
        }
        System.out.println("程序退出~~~");
    }
}

class ArrayStack {
    //数组栈
    private int[] stack;//数组栈
    private int maxSize;//栈大小
    private int top = -1;//栈顶，-1表示没有数据

    public ArrayStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //栈满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    //栈空
    public boolean isEmpty() {
        return top == -1;
    }

    //入栈
    public void push(int value) {
        if (isFull()) {
            System.out.println("栈满了");
            return;
        }
        top++;
        stack[top] = value;
    }

    //出栈
    public int pop() {
        if (isEmpty()) {
            throw new NullPointerException("栈空");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //遍历栈
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空");
        }
        //遍历栈是从栈顶开始的
        for (int i = top; i >= 0; i--) {
            System.out.printf("stack[%d]=%d\n", i, stack[i]);
        }
    }
}
